package cn.wetcland.urban.common.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 接口传时间类型参数转换
 */
@Configuration
public class DateConfig {
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    @Bean
    public Converter<String, Date> dateConverter(){
        return new Converter<String, Date>() {
            @SneakyThrows
            @Override
            public Date convert(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                source = source.trim();
                try {
                    if (source.contains("-")) {
                        SimpleDateFormat formatter;
                        if (source.contains(":")) {
                            formatter = new SimpleDateFormat(DATE_TIME_PATTERN);
                        } else {
                            formatter = new SimpleDateFormat(DATE_PATTERN);
                        }
                        Date dtDate = formatter.parse(source);
                        return dtDate;
                    } else if (source.matches("^\\d+$")) {
                        Long lDate = new Long(source);
                        return new Date(lDate);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(String.format("parser %s to Date fail", source));
                }
                throw new RuntimeException(String.format("parser %s to Date fail", source));
            }
        };
    }

    @Bean
    public Converter<String, LocalDate> localDateConverter(){
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String s) {
                return LocalDate.parse(s);
            }
        };
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter(){
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                if (source.trim().length() == 0) {
                    return null;
                }
                // 先尝试ISO格式: 2019-07-15T16:00:00
                try {
                    return LocalDateTime.parse(source);
                } catch (Exception e) {
                    return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
                }
            }
        };
    }
}
